package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.Employee;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Viktar Liaskovich
 */
public class EmployeeDao extends BaseDaoObject<Employee> {
    public Employee getByKey(Serializable key) {
        return (Employee) getHibernateTemplate().get(Employee.class, key);
    }

    public Set<String[]> getEmployeesByName(final String username) {
        return (Set<String[]>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Set<String[]> result = new HashSet<String[]>();
                List<Object[]> list = session.createQuery("select employee.firstName, employee.lastName from Employee employee, Login login " +
                        "where login.login = :username and employee.location = login.location ").
                        setParameter("username", username, Hibernate.STRING).list();
                if (list != null && !list.isEmpty()) {
                    for (Object[] obj : list) {
                        result.add(new String[]{String.valueOf(obj[0]), String.valueOf(obj[1])});
                    }
                }
                return result;
            }
        });
    }

    public Set<Employee> getEmployees(final String username) {
        return (Set<Employee>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List<Employee> result = session.createQuery("select employee from Employee employee, Login login " +
                        "where login.login = :username and employee.location = login.location ").
                        setParameter("username", username, Hibernate.STRING).list();

                return result == null || result.isEmpty() ? new HashSet<Employee>() : new HashSet<Employee>(result);
            }
        });
    }
}